# -*- coding;utf-8 -*-
"""
File name : Pdf2OtherMiner.PY
Program IDE : PyCharm
Create file time: 2025/5/26 11:56
File Create By Author : 朱清闯
"""
import requests
import time


def mineru(file_url: str):
    url = 'https://mineru.net/api/v4/extract/task'
    header = {
        'Content-Type': 'application/json',
        "Authorization": "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiIxMTkwMzUiLCJyb2wiOiJST0xFX1JFR0lTVEVSIiwiaXNzIjoiT3BlblhMYWIiLCJpYXQiOjE3NDgyMzE2MjcsImNsaWVudElkIjoibGt6ZHg1N252eTIyamtwcTl4MnciLCJwaG9uZSI6IiIsIm9wZW5JZCI6bnVsbCwidXVpZCI6IjhjNzc4MTZkLTZmY2MtNDZhZS1iYzVkLTYyZTg3NDE2YmFkNSIsImVtYWlsIjoiIiwiZXhwIjoxNzQ5NDQxMjI3fQ.meQO8Mc847dTv8A2_FIndSKXmCsKBCQszfx1zuWoab1xiGWC3dpSs8v7YeAF2DOYY_ohMQVmjzJn0qJFFFrVZA"
    }

    data = {
        'url': file_url,
        'is_ocr': True,
        'enable_formula': False,
    }

    res = requests.post(url, headers=header, json=data)
    print(res.status_code)
    print(res.json())
    print(res.json()["data"])
    task_id = ''
    for i in range(100):
        status = res.status_code
        if status == "success":
            print("get task_id success!")
            task_id = res.json()["data"]['task_id']
            break
        elif status == "failed":
            break
        elif status == "processing":
            print(status)
            time.sleep(3)
    else:
        print(f"Fails to deal with get task id after 100 retries")
    if task_id == '':
        print('get task_id fail!')
        return False, ''
    url = f'https://mineru.net/api/v4/extract/task/{task_id}'
    res = requests.get(url, headers=header)
    print(res.status_code)
    print(res.json())
    print(res.json()["data"])
    file_url = ''
    for i in range(100):
        status = res.status_code
        if status == "success":
            print("get result success!")
            result = res.json()["data"]
            data = result.data
            code = result.code
            if code == 0:
                if data.state in ['pending', 'running', 'converting']:
                    continue
                elif data.state == 'failed':
                    return False, ''
                elif data.state == 'done':
                    file_url = data.full_zip_url
                    break
            break
        elif status == "failed":
            break
        elif status == "processing":
            print(status)
            time.sleep(3)
    else:
        print(f"Fails to deal with get task id after 100 retries")
    if file_url == '':
        return False, ''
    return True, file_url
